// src-tauri/src/torrent_parser.rs
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;

use crate::complete_bittorrent::{TorrentFile, FileInfo};

pub struct TorrentParser;

impl TorrentParser {
    pub fn parse_torrent_file(file_path: &Path) -> Result<TorrentFile, String> {
        let file_content = std::fs::read(file_path)
            .map_err(|e| format!("Failed to read torrent file: {}", e))?;

        Self::parse_torrent_data(&file_content)
    }

    pub fn parse_torrent_data(data: &[u8]) -> Result<TorrentFile, String> {
        let decoded = bencode::from_iter(data.iter().copied())
            .map_err(|e| format!("Failed to decode torrent data: {}", e))?;

        Self::build_torrent_file(decoded)
    }

    fn build_torrent_file(decoded: bencode::Bencode) -> Result<TorrentFile, String> {
        let info_dict = match decoded {
            bencode::Bencode::Dict(dict) => dict.get(b"info").ok_or("Missing info dictionary in torrent")?,
            _ => return Err("Expected dictionary at top level".to_string())
        };

        // 重新编码info字典获取info_hash
        let info_bencoded = bencode::encode(info_dict)
            .map_err(|e| format!("Failed to encode info dict: {}", e))?;

        let info_hash = Self::compute_info_hash(&info_bencoded);

        // 解析文件信息
        let (name, files, total_length, piece_length, pieces) = 
            Self::parse_info_dict(info_dict)?;

        // 解析Tracker列表
        let trackers = Self::parse_trackers(&decoded)?;

        Ok(TorrentFile {
            info_hash,
            name,
            total_length,
            piece_length,
            pieces,
            files,
            trackers,
        })
    }

    fn parse_info_dict(info_dict: &bencode::Bencode) -> Result<(String, Vec<FileInfo>, u64, u64, Vec<String>), String> {
        // 解析torrent文件的info字典
        // 简化实现，实际需要处理单文件和多文件情况
        Ok((
            "example.torrent".to_string(),
            Vec::new(),
            0,
            0,
            Vec::new(),
        ))
    }

    fn parse_trackers(decoded: &bencode::Bencode) -> Result<Vec<String>, String> {
        let mut trackers = Vec::new();
        
        // 确保decoded是一个字典
        let dict = match decoded {
            bencode::Bencode::Dict(dict) => dict,
            _ => return Ok(trackers)
        };

        // 解析announce
        if let Some(bencode::Bencode::Bytes(announce)) = dict.get(b"announce") {
            if let Ok(announce_str) = String::from_utf8(announce.clone()) {
                trackers.push(announce_str);
            }
        }

        // 解析announce-list
        if let Some(bencode::Bencode::List(announce_list)) = dict.get(b"announce-list") {
            for tier in announce_list {
                if let bencode::Bencode::List(urls) = tier {
                    for url in urls {
                        if let bencode::Bencode::Bytes(url_bytes) = url {
                            if let Ok(url_str) = String::from_utf8(url_bytes.clone()) {
                                trackers.push(url_str);
                            }
                        }
                    }
                }
            }
        }

        Ok(trackers)
    }

    fn compute_info_hash(info_bencoded: &[u8]) -> String {
        use sha1::{Sha1, Digest};
        let mut hasher = Sha1::new();
        hasher.update(info_bencoded);
        format!("{:x}", hasher.finalize())
    }
}